package com.thinvent.nj.ais.inteceptor;

import com.alibaba.fastjson.JSON;
import com.thinvent.nj.common.util.WebContextUtil;
import com.thinvent.nj.ais.entity.Log;
import com.thinvent.nj.ais.entity.User;
import com.thinvent.nj.ais.shiro.UserContextUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;

/**
 * 系统调用日志拦截器，用于rest服务接口调用统计
 * @author liupeijun
 */
@Component
public class StatisticInterceptor implements HandlerInterceptor {

    private static final Logger logger = LoggerFactory.getLogger(StatisticInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Log log = new Log();

        log.setIp(WebContextUtil.getClientIp(request));
        log.setUri(WebContextUtil.getRelativeUrl(request));

        boolean isAjax = WebContextUtil.isAjaxRequest(request);

        if (isAjax) {
            log.setType("1");
        } else {
            log.setType("2");
        }

        log.setMethod(request.getMethod());

        log.setParams(JSON.toJSONString(request.getParameterMap()));

        User user = UserContextUtil.currentUser();

        if (user != null) {
            log.setUsername(user.getUsername());
        } else {
            log.setUsername("undefined");
        }

        log.setReqDate(new Date());

        request.setAttribute("log", log);

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        Log log = (Log) request.getAttribute("log");

        // 当前时间
        long currentMillis = System.currentTimeMillis();
        log.setCostMills(currentMillis - log.getReqDate().getTime());

        log.setStatusCode(response.getStatus());

        logger.info("===========> execute log : {}", log);

    }
}
